<template>
  <div class="breadcrumb-container">
    <el-breadcrumb separator="/">
      <el-breadcrumb-item
        v-for="(item, index) in breadcrumbList"
        :key="item.path"
        :to="{ path: item.path }"
        :class="{ 'last-item': index === breadcrumbList.length - 1 }"
      >
        {{ item.meta?.title || item.name || '首页' }}
      </el-breadcrumb-item>
    </el-breadcrumb>
  </div>
</template>

<script setup lang="ts">
import { ref, computed, onMounted, watch } from 'vue'
import { useRouter, useRoute } from 'vue-router'
import type { RouteRecordRaw } from 'vue-router'
import { usePermissionStore } from '@/store/modules/permission'

const router = useRouter()
const route = useRoute()
const permissionStore = usePermissionStore()
const breadcrumbList = ref<Array<{ path: string; meta?: any; name?: string }>>([])

/**
 * 生成面包屑导航列表
 */
const generateBreadcrumb = () => {
  const matched = route.matched
  const matchedFilter = matched.filter(item => item.meta && item.meta.title)
  
  // 如果没有匹配的路由，显示默认面包屑
  if (matchedFilter.length === 0) {
    breadcrumbList.value = [{ path: '/', meta: { title: '首页' } }]
    return
  }
  
  // 处理首页路由
  const homePath = '/dashboard'
  const homeRoute = {
    path: homePath,
    meta: { title: '首页' }
  }
  
  // 创建面包屑列表
  const breadcrumb: Array<{ path: string; meta?: any; name?: string }> = [homeRoute]
  
  // 添加匹配的路由到面包屑
  matchedFilter.forEach((item, index) => {
    // 跳过重复的首页路由
    if (item.path === homePath && index === 0) {
      return
    }
    
    breadcrumb.push({
      path: item.path,
      meta: item.meta,
      name: item.name
    })
  })
  
  breadcrumbList.value = breadcrumb
}

// 监听路由变化，重新生成面包屑
watch(
  () => route.path,
  () => {
    generateBreadcrumb()
  },
  { immediate: true }
)

// 组件挂载时生成面包屑
onMounted(() => {
  generateBreadcrumb()
})
</script>

<style lang="scss" scoped>
.breadcrumb-container {
  margin: 0 16px;
  font-size: 14px;
  line-height: 1;
  
  .last-item {
    color: var(--el-text-color-primary);
    font-weight: 500;
  }
}
</style>